<template>
  <div class="notes">
    <div class="main">
      <div class="header">
        <el-form :inline="true">
          <el-form-item label="标题">
            <el-input placeholder="请输入标题" v-model="findNotesQuery.title"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="findNotesQuery.status" placeholder="请选择状态">
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="getNotesWithQuery">查询</el-button>
            <el-button @click="replace">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="router.push(`/addNotes/${-1}`)">
              <el-icon><Plus /></el-icon>
              <span>新增动态</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="deleteBatch">
              <el-icon><Minus /></el-icon>
              <span>批量删除</span>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="body" v-if="notesList.length > 0">
        <el-table :data="notesList" stripe @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="30"></el-table-column>
          <el-table-column label="标题" prop="title"></el-table-column>
          <el-table-column label="标签" width="80">
            <template #default="scope">
              <el-tag v-for="item in scope.row.tags" :key="item.id">{{ item.name }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="封面" prop="coverUrl" show-overflow-tooltip></el-table-column>
          <el-table-column label="浏览量" prop="viewCount"></el-table-column>
          <el-table-column label="评论数量" prop="commentCount" width="80"></el-table-column>
          <el-table-column label="点赞数量" prop="likeCount" width="80"></el-table-column>
          <el-table-column label="是否置顶" prop="isTop" width="80">
            <template #default="scope">
              <span
                :class="scope.row.isTop === 0 ? 'blur' : 'red'"
                @click="updateIsTop(scope.row.isTop === 0 ? 1 : 0, scope.row.id)"
              >
                {{ scope.row.isTop === 0 ? '置顶' : '取消置顶' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="更新状态" prop="latest" width="110">
            <template #default="scope">
              <span
                :class="scope.row.latest === 0 ? 'blur' : 'red'"
                @click="updateLatest(scope.row.latest === 0 ? 1 : 0, scope.row.id)"
              >
                {{ scope.row.latest === 0 ? '最近更新' : '取消最近更新' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" width="80">
            <template #default="scope">
              <span
                :class="computedStatusColor(scope.row.status)"
                @click="updateStatus(scope.row.status === 0 ? 1 : 0, scope.row.id)"
              >
                {{ computedStatus(scope.row.status) }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            prop="createTime"
            show-overflow-tooltip
            width="120"
          ></el-table-column>
          <el-table-column
            label="修改时间"
            prop="updateTime"
            show-overflow-tooltip
            width="120"
          ></el-table-column>
          <el-table-column label="操作" width="170">
            <template #default="scope">
              <el-button type="danger" :text="true" @click="deleteNote(scope.row.id)"
                >删除</el-button
              >
              <el-button
                type="primary"
                :text="true"
                @click="router.push(`/addNotes/${scope.row.id}`)"
                >修改</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-empty v-else></el-empty>
      <div class="page">
        <el-pagination
          v-model:current-page="findNotesQuery.page"
          v-mdoel:page-size="findNotesQuery.pageSize"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handlePageSizeChange"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { deleteBatchService, getNotesListQuerySevice, updateBatchStatusService } from '@/api/Notes'
import { Plus, Minus } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 接收返回数据列表
const notesList = ref([])
const total = ref(null)

const findNotesQuery = ref({
  page: 1,
  pageSize: 9,
  title: '',
  status: null,
})

/**
 * 批量修改动态状态字段
 */
const statusObj = ref({
  id: '',
  isTop: null,
  latest: null,
  status: null,
})
// 修改置顶状态
const updateIsTop = (isTop, id) => {
  statusObj.value.id = id
  statusObj.value.isTop = isTop
  const res = updateBatchStatusService(statusObj.value).then(() => {
    statusObj.value.id = ''
    statusObj.value.isTop = null
    getNotesList(findNotesQuery.value)
  })
}
// 修改更新状态
const updateLatest = (latest, id) => {
  statusObj.value.id = id
  statusObj.value.latest = latest
  updateBatchStatusService(statusObj.value).then(() => {
    statusObj.value.id = ''
    statusObj.value.latest = null
    getNotesList(findNotesQuery.value)
  })
}
// 修改动态状态
const updateStatus = (status, id) => {
  statusObj.value.id = id
  statusObj.value.status = status
  updateBatchStatusService(statusObj.value).then(() => {
    statusObj.value.id = ''
    statusObj.value.status = null
    getNotesList(findNotesQuery.value)
  })
}

/**
 * 删除动态数据
 */
const noteIds = ref([])
const deleteNote = (id) => {
  noteIds.value.push(id)
  deleteBatchService(noteIds.value).then(() => {
    getNotesList(findNotesQuery.value)
  })
}
const handleSelectionChange = (row) => {
  const obj = JSON.parse(JSON.stringify(row))
  noteIds.value = []
  obj.forEach((item) => {
    noteIds.value.push(item.id)
  })
}
const deleteBatch = () => {
  if (noteIds.value.length === 0) {
    ElMessage.error('未选中任何数据')
  } else {
    ElMessageBox.confirm(`你确认删除这${noteIds.value.length}条数据吗?`, 'Warning', {
      type: 'error',
      confirmButtonText: '确认',
      cancelButtonText: '取消',
    }).then(() => {
      deleteBatchService(noteIds.value).then(() => {
        getNotesList(findNotesQuery.value)
      })
    })
  }
}

// 计算动态状态
const computedStatus = (status) => {
  if (status === 0) {
    return '启用'
  } else if (status === 1) {
    return '禁用'
  } else {
    return '草稿'
  }
}
const computedStatusColor = (status) => {
  if (status === 0) {
    return 'blur'
  } else if (status === 1) {
    return 'red'
  } else {
    return 'green'
  }
}

/**
 * 分页相关
 */
const handlePageSizeChange = (pageSize) => {
  findNotesQuery.value.pageSize = pageSize
  getNotesList(findNotesQuery.value)
}
const handlePageChange = (page) => {
  findNotesQuery.value.page = page
  getNotesList(findNotesQuery.value)
}
/**
 * 条件查询动态数据
 */
const getNotesWithQuery = () => {
  getNotesList(findNotesQuery.value)
}
/**
 * 重置
 */
const replace = () => {
  getNotesList({
    page: 1,
    pageSize: 9,
    title: '',
    status: null,
  })
}
/**
 * 获取动态数据列表
 * @param query
 */
const getNotesList = async (query) => {
  const { data } = await getNotesListQuerySevice(query)
  total.value = data.total
  notesList.value = data.records
}

onMounted(() => {
  getNotesList(findNotesQuery.value)
})
</script>

<style lang="scss" scoped>
.notes {
  background-color: #f3f4f5;
  padding: 15px;

  .main {
    padding: 20px;
    border-radius: 7px;
    min-height: 100vh;
    background-color: #fff;

    .header {
      :deep(.el-select__wrapper) {
        width: 150px;
      }
    }

    .page {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }
}

.blur {
  cursor: pointer;
  color: #37b4fd;
}
.red {
  cursor: pointer;
  color: red;
}
.green {
  color: #43e478;
  pointer-events: none;
}

::v-deep.el-table .cell {
  text-align: center !important;
}
</style>